package com.wetsion.securityoauthdemo.server.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wetsion.securityoauthdemo.server.dao.*;
import com.wetsion.securityoauthdemo.server.entity.Permission;
import com.wetsion.securityoauthdemo.server.entity.RolePermission;
import com.wetsion.securityoauthdemo.server.entity.User;
import com.wetsion.securityoauthdemo.server.entity.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * Created by wetsion on 2019/3/2.
 */
@Service
public class UserService implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    UserRoleMapper userRoleMapper;

    @Autowired
    RolePermissionMapper rolePermissionMapper;

    @Autowired
    PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", s);
        User user = userMapper.selectOne(wrapper);
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException(s);
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        QueryWrapper<UserRole> roleWrapper = new QueryWrapper<>();
        roleWrapper.eq("user_id", user.getId());
        List<UserRole> roles = userRoleMapper.selectList(roleWrapper);
        for (UserRole userRole: roles) {
            List<RolePermission> rolePermissions = rolePermissionMapper.selectList(
                    new QueryWrapper<RolePermission>().eq("role_id", userRole.getRoleId()));
            for (RolePermission rolePermission : rolePermissions) {
                Permission permission = permissionMapper.selectById(rolePermission.getPermissionId());
                authorities.add(new SimpleGrantedAuthority(permission.getCode()));
            }
        }
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(), user.getPassword(), authorities);
    }
}
